<?php

class TournamentManagementController extends Controller {

	public $layout = 'main';
	
	public function accessRules() {
		return array(
				array('deny',
						'actions' => array( 'index', 'checkTournamentName' ),
						'users' => array('?'),
				)
		);
	}
	
	public function filters() {
		return [ 'accessControl'];
	}
	
    public function actionIndex() {
        $this->render('index');
    }

    public function actionSetCurrentTournament( $idTournament ){
    	/* Check if users is registered in tournament */
    	$newCurrTournament = TournamentsUsers::model()->findByPk( 
    			[ 'idTournament' => $idTournament, 'idUser' => Yii::app()->user->id ] );
    	
    	if( $newCurrTournament ){
    		/* Set current tournament byDefault = 0 */
    		$currTournament = TournamentsUsers::model()->findByPk( 
    				[ 'idTournament' => Yii::app()->user->currentTournament, 'idUser' => Yii::app()->user->id ] );
    		$currTournament->byDefault = 0;
    		$currTournament->save();
    		
    		/* Set new tournament as default */
    		$newCurrTournament->byDefault = 1;
    		$newCurrTournament->save();
    		Yii::app()->user->setState( 'currentTournament', $idTournament );
    	}
    	$this->redirect( '/news' );
    }
    
    public function actionCheckTournamentName($name) {
        $tournament = Tournaments::model()->findByAttributes(['name' => $name]);
        
        if( !$tournament ) {
            $this->renderJSON( ['result' => 'OK'] );
        }else{
            $this->renderJSON( ['error' => Yii::t('tournament_management', 'Name already exists')] );
        }
        
    }

}
